package vip.liux.contracts.models.point;

import org.springframework.stereotype.Component;
import vip.liux.contracts.repositories.point.IPointsTransactionRepository;
import vip.liux.contracts.shared.enums.point.TransactionStatus;
import vip.liux.core.exception.BusinessException;

@Component
public class PointsTransactionDomainService {
    private final IPointsTransactionRepository transactionRepo;

    public PointsTransactionDomainService(IPointsTransactionRepository transactionRepo) {
        this.transactionRepo = transactionRepo;
    }

    public PointsTransaction savePointsTransaction(PointsTransaction transaction) {
        transactionRepo.findByRelatedNoAndRuleCode(transaction.getRelatedNo(), transaction.getRuleCode())
                .ifPresent(existingTransaction -> {
                    // 如果已存在相同的外部交易号，抛出异常或处理逻辑
                    throw new BusinessException("RELATED_NO_ALREADY_EXISTS", "订单号已存在: " + transaction.getRelatedNo());
                });
        return transactionRepo.save(transaction);
    }

    public void refundTransaction(PointsTransaction originalTransaction) {
        int updated = transactionRepo.updateStatusByIdAndStatus(
                TransactionStatus.COMPLETED,
                originalTransaction.getId(),
                TransactionStatus.REFUND
        );

        if (updated < 1) {
            throw new BusinessException("退款更新失败", "退款更新失败: " + originalTransaction.getTransactionNo());
        }
    }
}